# -*- coding=utf-8
from qcloud_cos import CosConfig
from qcloud_cos import CosS3Client
import sys
import logging
from config import CONFIG
import requests


# 正常情况日志级别使用INFO，需要定位时可以修改为DEBUG，此时SDK会打印和服务端的通信信息
# logging.basicConfig(level=logging.INFO, stream=sys.stdout)


class CosClient:
    config = CosConfig(Region=CONFIG.COS_REGION,
                       SecretId=CONFIG.COS_SECRET_ID,
                       SecretKey=CONFIG.COS_SECRET_KEY,
                       Token=CONFIG.COS_TOKEN,
                       Domain=CONFIG.COS_DOMAIN,
                       Scheme=CONFIG.COS_SCHEME)
    client = CosS3Client(config)

    @classmethod
    def put_file_stream(cls, file_path, fp):
        """

        :param file_path: "/asd/asdfs/dsad.jpg"
        :param body: with open('picture.jpg', 'rb') as fp:
        :return:
        """
        res = cls.client.put_object(
            Bucket=CONFIG.COS_BUCKET,
            Body=fp,
            Key=file_path,
            StorageClass='STANDARD',
            EnableMD5=False
        )
        return res['ETag']

    @classmethod
    def put_file_bytes(cls, file_path, body):
        res = cls.client.put_object(
            Bucket=CONFIG.COS_BUCKET,
            Body=body,
            Key=file_path,
            EnableMD5=False
        )
        return res['ETag']

    @classmethod
    def put_file_net(cls, file_path, file_url):
        stream = requests.get(file_url)

        res = cls.client.put_object(
            Bucket=CONFIG.COS_BUCKET,
            Body=stream,
            Key=file_path
        )
        return res['ETag']

    @classmethod
    def upload_file(cls, file_path, local_file_path):
        res = cls.client.upload_file(
            Bucket=CONFIG.COS_BUCKET,
            LocalFilePath=local_file_path,
            Key=file_path,
            PartSize=1,
            MAXThread=10,
            EnableMD5=False
        )
        print(res)
        return res['ETag']


if __name__ == '__main__':
    CosClient.upload_file("/temp/111.jpeg", "/home/herb/Pictures/bg/bg.jpeg")